package org.raymond.iworks.study.netty.atguigu.netty.codec2;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.raymond.iworks.study.netty.atguigu.netty.codec2.model.MyMessage;
import org.raymond.iworks.study.netty.atguigu.netty.codec2.model.Student;
import org.raymond.iworks.study.netty.atguigu.netty.codec2.model.Worker;

import java.util.Random;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class ProtoClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 随机传输一个student或worker对象
        int random = new Random().nextInt(3);
        MyMessage myMessage = null;
        //Student student = Student.newBuilder().setId(1).setName("diablo").build();
        switch (random){
            case 0:
            case 1:
                myMessage = MyMessage.newBuilder()
                        .setDataType(MyMessage.DataType.StudentType)
                        .setStudent(Student.newBuilder().setId(2).setName("diablo").build()).build();
                break;
            default:
                myMessage = MyMessage.newBuilder()
                        .setDataType(MyMessage.DataType.WorkerType)
                        .setWorker(Worker.newBuilder().setAge(36).setName("java").build()).build();
                break;
        }
        ctx.writeAndFlush(myMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        log.info("{}->: {}", ctx.channel().remoteAddress().toString(), buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("{}", cause.getMessage());
        ctx.close();
    }
}
